<?php

namespace App\Http\Traits;

use Illuminate\Http\Request;

trait HandlesResourceOperations
{
    /**
     * 显示资源详情
     *
     * @param string $modelClass 模型类名
     * @param int|string $id 资源ID
     * @param array $with 需要预加载的关联
     * @param string|null $resourceClass 资源类名
     * @return \Illuminate\Http\JsonResponse
     */
    protected function showResource(string $modelClass, $id, array $with = [], ?string $resourceClass = null)
    {
        $query = $modelClass::query();
        if (!empty($with)) {
            $query->with($with);
        }
        
        $model = $query->findOrFail($id);
        
        if ($resourceClass) {
            return $this->success(new $resourceClass($model), '获取成功');
        }
        
        return $this->success($model, '获取成功');
    }

    /**
     * 更新资源
     *
     * @param string $modelClass 模型类名
     * @param Request $request
     * @param int|string $id 资源ID
     * @param object|null $service 服务实例
     * @param array $with 需要预加载的关联
     * @param string|null $resourceClass 资源类名
     * @return \Illuminate\Http\JsonResponse
     */
    protected function updateResource(
        string $modelClass,
        Request $request,
        $id,
        ?object $service = null,
        array $with = [],
        ?string $resourceClass = null
    ) {
        $model = $modelClass::findOrFail($id);
        
        if ($service && method_exists($service, 'update')) {
            $model = $service->update($model, $request->validated());
        } else {
            $model->update($request->validated());
            $model->refresh();
        }
        
        // 重新加载关联
        if (!empty($with)) {
            $model->load($with);
        }
        
        if ($resourceClass) {
            return $this->success(new $resourceClass($model), '更新成功');
        }
        
        return $this->success($model, '更新成功');
    }

    /**
     * 删除资源
     *
     * @param string $modelClass 模型类名
     * @param int|string $id 资源ID
     * @param object|null $service 服务实例
     * @return \Illuminate\Http\JsonResponse
     */
    protected function destroyResource(string $modelClass, $id, ?object $service = null)
    {
        $model = $modelClass::findOrFail($id);
        
        try {
            if ($service && method_exists($service, 'delete')) {
                $service->delete($model);
            } else {
                $model->delete();
            }
            
            return $this->success(null, '删除成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 400);
        }
    }
}
